import { defineStore } from 'pinia'
import Dayjs from 'dayjs'

//login
import { reqLogin, reqUserInfo } from '../api/login';
import { getToken, removeToken, setToken } from '../utils/token-utils';
// 请求
import {
	reqGetCenter,
	reqGetMembers,
	reqGetSkills,
	reqGetAvocation,
	reqGetSearch,
	reqSaveInfo,
} from '../api/center/index'
import city from '../mock/center/city.json'

export const useUserInfoStore = defineStore('userInfo', {
	state: () => ({
		token: getToken() as string,
		access_token: 'b274c872-4c0b-476a-9ec4-3a93861296ce',
		nickName: '',
		// 头像
		avatar: '',
		// 个人爱好
		avocation: [],
		// 会员信息
		members: <any>[],
		// 总价
		totalPrice: 0,
		// 技能等级
		skills: [],
		// 性别
		gender: '男',
		// 生日
		birthday: '',
		// 自身等级
		skill: '',
		skillLevel: 0,
		// 全部城市信息
		city,
		// 自身城市信息
		myCity: '',
		// 标题
		title: '资源动态',
		// 等级
		level: 1,
		// 所有的爱好
		avocations: {
			content: [],
			number: 0,
		},
		// 搜索的爱好列表
		searchList: [],
		// 历史搜索
		historySearch: [],
	}),
	actions: {
		// 获取用户信息
		async getCenter() {
			let result = await reqGetCenter()
			this.avatar = result?.avatar
			this.nickName = result?.account
			this.skill = result.moreBackup.skillLevelName
			this.avocation = result.avocation
			this.skillLevel = result.moreBackup.skillLevel
			this.myCity = result.moreBackup.address
			this.level = result.level
			this.birthday = Dayjs(result.moreBackup.birthDate).format(
				'YYYY-MM-DD'
			)
		},
		// 获取会员信息
		async getMembers() {
			let result = await reqGetMembers()
			this.members = result
			this.totalPrice = result[2].data.total_price
		},
		// 获取技能信息
		async getSkills() {
			let result = await reqGetSkills()
			this.skills = result
		},
		// 获取全部爱好
		async getAvocation(num: any) {
			let result = await reqGetAvocation(num)
			this.avocations.content.push(...result.content)
			this.avocations.number = result.number
		},
		// 搜索爱好
		async getSearchList(searchName) {
			let result = await reqGetSearch(searchName)
			this.searchList = result
		},
		async login(phone: string, password: string) {
			try {
				let result = await reqLogin({ phone, password });
				this.token = result.data.token;
				// console.log(useUserInfoStore().token);
				//持久化存储token
				setToken(result.data.token);
				return 'ok'
			} catch (error) {
				return Promise.reject('失败');
			}
		},
		//获取用户信息
		async getInfo() {
			try {
				let result = await reqUserInfo();
				console.log(useUserInfoStore().token);
				//获取用户信息:头像、名字
				this.nickName = result.data.name;
				this.avatar = 'https://wpimg.wallstcn.com/f778738c-e4f8-4870-b634-56703b4acafe.gif';

				return 'ok'
			} catch (error) {
				return Promise.reject('失败');
			}
		},
	},
	getters: {
		// 总价格
	},
})
